package informed.matrix;

import java.util.Iterator;

import cern.colt.matrix.DoubleMatrix1D;
import cern.colt.matrix.DoubleMatrix2D;
import cern.colt.matrix.impl.DenseDoubleMatrix1D;

public class Utils {
	
	public static DoubleMatrix1D addVectors(DoubleMatrix1D a, DoubleMatrix1D b){
		DoubleMatrix1D c = new DenseDoubleMatrix1D(a.size());
		for(int i = 0; i < a.size(); i++){
			c.setQuick(i, a.getQuick(i) + b.getQuick(i));
		}
		return c;
	}
	
	public static DoubleMatrix1D multByScalar(DoubleMatrix1D a, double s){
		DoubleMatrix1D b = new DenseDoubleMatrix1D(a.size());
		for(int i = 0; i < a.size(); i++){
			b.setQuick(i, a.getQuick(i)*s);
		}
		return b;
	}
	
	public static DoubleMatrix1D multMatrixRowByScalar(DoubleMatrix2D matrix, int row, double s){
		DoubleMatrix1D result = new DenseDoubleMatrix1D(matrix.columns());
		for(int j = 0; j < matrix.columns(); j++){
			result.setQuick(j, matrix.getQuick(row, j)*s);
		}
		return result;
	}
	
	public static DoubleMatrix1D multMatrixColByScalar(DoubleMatrix2D matrix, int col, double s){
		DoubleMatrix1D result = new DenseDoubleMatrix1D(matrix.rows());
		for(int i = 0; i < matrix.rows(); i++){
			result.setQuick(i, matrix.getQuick(i, col)*s);
		}
		return result;
	}

	public static DoubleMatrix1D multMatrixAndSparseVector(DoubleMatrix2D matrix, SparseVector vector){
		DoubleMatrix1D result = new DenseDoubleMatrix1D(matrix.rows());
		Iterator<Integer> keys = vector.getIndices();
		while(keys.hasNext()){
			int j = keys.next();
			double vj = vector.get(j);
			for(int i = 0; i < matrix.rows(); i++){			
				result.setQuick(i, result.getQuick(i) + vj*matrix.getQuick(i, j));
			}
		}
		return result;
	}
	
	public static double multMatrixRowAndVector(DoubleMatrix2D matrix, int row, DoubleMatrix1D vector){
		double result = 0.0;
		for(int j = 0; j < matrix.columns(); j++){
			result += matrix.getQuick(row, j)*vector.getQuick(j);
		}
		return result;
	}
	
	public static double multMatrixColAndVector(DoubleMatrix2D matrix, int col, DoubleMatrix1D vector){
		double result = 0.0;
		for(int i = 0; i < matrix.rows(); i++){
			result += matrix.getQuick(i, col)*vector.getQuick(i);
		}
		return result;
	}
	
	public static SparseVector transform(DoubleMatrix1D vector){
		SparseVector result = new SparseVector();
		for(int i = 0; i < vector.size(); i++){
			if(vector.getQuick(i) != 0)
				result.set(i, vector.getQuick(i));
		}
		return result;
	}

}
